<?php

// This is a PLUGIN TEMPLATE.

// Copy this file to a new name like abc_myplugin.php.  Edit the code, then
// run this file at the command line to produce a plugin for distribution:
// $ php abc_myplugin.php > abc_myplugin-0.1.txt

// Plugin name is optional.  If unset, it will be extracted from the current
// file name. Plugin names should start with a three letter prefix which is
// unique and reserved for each plugin author ("abc" is just an example).
// Uncomment and edit this line to override:
$plugin['name'] = 'msd_admin_datepicker';

// Allow raw HTML help, as opposed to Textile.
// 0 = Plugin help is in Textile format, no raw HTML allowed (default).
// 1 = Plugin help is in raw HTML.  Not recommended.
# $plugin['allow_html_help'] = 1;

$plugin['version'] = '0.5';
$plugin['author'] = 'Matt Davis';
$plugin['author_uri'] = 'http://photographdaddy.com';
$plugin['description'] = 'Add a jQuery UI date picker to a field in the write tab.';

// Plugin load order:
// The default value of 5 would fit most plugins, while for instance comment
// spam evaluators or URL redirectors would probably want to run earlier
// (1...4) to prepare the environment for everything else that follows.
// Values 6...9 should be considered for plugins which would work late.
// This order is user-overrideable.
$plugin['order'] = '5';

// Plugin 'type' defines where the plugin is loaded
// 0 = public       : only on the public side of the website (default)
// 1 = public+admin : on both the public and admin side
// 2 = library      : only when include_plugin() or require_plugin() is called
// 3 = admin        : only on the admin side
$plugin['type'] = '3';

// Plugin "flags" signal the presence of optional capabilities to the core plugin loader.
// Use an appropriately OR-ed combination of these flags.
// The four high-order bits 0xf000 are available for this plugin's private use
if (!defined('PLUGIN_HAS_PREFS')) define('PLUGIN_HAS_PREFS', 0x0001); // This plugin wants to receive "plugin_prefs.{$plugin['name']}" events
if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events

$plugin['flags'] = '3';

if (!defined('txpinterface'))
        @include_once('zem_tpl.php');

# --- BEGIN PLUGIN CODE ---
##################
#
#	msd_admin_datepicker for Textpattern
#	version 0.4
#	by Matt Davis
#	http://photographdaddy.com
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    A copy of the GNU General Public License is available at http://www.gnu.org/licenses/.
#
#    v0.2 - Added option to use datepicker for posted or expire date. 
#           Unable to set calendar using posted or expire value but selecting a date works.
#    v0.3 - Allow blank value for Date Custom Field preference.
#    v0.4 - Fixed link to Options in Help. (Thanks pieman)
#    v0.5 - Added icon from http://www.famfamfam.com/lab/icons/silk/
#
###################
define( 'MSD_DATEPICKER_PREFIX' , 'msd_dtpk' );//For MLP
global $msd_datepicker_strings; 
$msd_datepicker_strings = array( //For MLP
	'preferences'	=> 'Date Picker Preferences',
	'instructions'	=> 'Set the Date Custom Field to a jQuery Selector for the field you are using.<br/>Use a different source for the jQuery UI script and CSS. Maybe a local version?',
	'field' => 'Date Custom Field',
	'jqueryui' => 'jQuery UI URL',
	'tab' => 'Date Picker',
	'jqueryuicss' => 'jQuery UI CSS URL',
	'dateformat' => 'Date Picker Date Format',
	'articledate' => 'Use Date Picker for Posted Date?',
	'expiredate' => 'Use Date Picker for Expire Date?'
);
  
register_callback('msd_admin_datepicker_options', 'plugin_prefs.msd_admin_datepicker');
register_callback('msd_admin_daterpicker_install',
	'plugin_lifecycle.msd_admin_datepicker', 'installed');
register_callback('msd_admin_datepicker_uninstall',
	'plugin_lifecycle.msd_admin_datepicker', 'deleted');
register_callback('msd_datepicker_enumerate_strings' , 'l10n.enumerate_strings' );
add_privs('msd_admin_datepicker_options', 1);//Exten tab
add_privs('plugin_prefs.msd_admin_datepicker','1,2');
register_tab("extensions", "msd_admin_datepicker_options", msd_admin_datepicker_gTxt('tab'));//Exten Tab
register_callback("msd_admin_datepicker_options", "msd_admin_datepicker_options");//Exten Tab
register_callback("msd_admin_datepicker", "article");
switch(gps('msd_dtpkr')) {
	case 'jquery':
		msd_admin_datepicker_icon_jquery();
		break;
	case 'famfam':
		msd_admin_datepicker_icon_fam_fam();
		break;
	default:
		break;
}
msd_admin_datepicker_install();
#
#Add javascript and css to Admin Write Tab.
#
function msd_admin_datepicker($event, $step)
{
global $msd_datepicker_customfield, $msd_datepicker_jqueryui, $msd_datepicker_jqueryui_css, 
	$msd_datepicker_format, $msd_datepicker_posted,$msd_datepicker_expire;
$msd_iconpath= hu . "textpattern/?msd_dtpkr=famfam";
echo <<<msd_date_js
	<link href="$msd_datepicker_jqueryui_css" rel="stylesheet" type="text/css" />
	<script src='$msd_datepicker_jqueryui' type='text/javascript'></script>
	<script type="text/JavaScript">
msd_date_js;
if ($msd_datepicker_posted==1){
echo <<<msd_date_js
	function updateLinked(date) {
		$('input[name=month]').val(date.substring(0,2));
		$('input[name=day]').val(date.substring(3,5));
		$('input[name=year]').val(date.substring(6,10));
	}
msd_date_js;
}
if ($msd_datepicker_expire==1){
echo <<<msd_date_js
	function updateLinkedExpire(date) {
		$('input[name=exp_month]').val(date.substring(0,2));
		$('input[name=exp_day]').val(date.substring(3,5));
		$('input[name=exp_year]').val(date.substring(6,10));
	}
msd_date_js;
}
if ($msd_datepicker_customfield != ''){
echo <<<msd_date_js
	$(document).ready( function(){
		$('$msd_datepicker_customfield').datepicker({ dateFormat: '$msd_datepicker_format' });
	});
msd_date_js;
}
if ($msd_datepicker_posted==1){
echo <<<msd_date_js
	$(document).ready( function(){
		$('input[name=day]').after('<input type="hidden" size="10" id="linkedDatepicker" disabled="disabled">');
		postedDatepicker = $('#linkedDatepicker').datepicker({onSelect:updateLinked,
			showOn: 'both', buttonImageOnly: true, buttonImage: '$msd_iconpath'});
	});
msd_date_js;
}
if ($msd_datepicker_expire==1){
echo <<<msd_date_js
	$(document).ready( function(){
		$('input[name=exp_day]').after('<input type="hidden" size="10" id="linkedDatepickerExpire" disabled="disabled">');
		$('#linkedDatepickerExpire').datepicker({onSelect:updateLinkedExpire,
			showOn: 'both', buttonImageOnly: true, buttonImage: '$msd_iconpath'});
	});
msd_date_js;
}
echo "</script>";
}
#
#Preferences Page
#
function msd_admin_datepicker_options($event, $step){
global $msd_datepicker_customfield, $msd_datepicker_jqueryui, $msd_datepicker_jqueryui_css, 
	$msd_datepicker_format, $msd_datepicker_posted, $msd_datepicker_expire;
include_once txpath . '/include/txp_prefs.php';
if (ps("save")) {
	prefs_save();
	header("Location: index.php?event=msd_admin_datepicker_options");
	}
pagetop(msd_admin_datepicker_gTxt("preferences"));
echo form(startTable("list").
tr(tdcs(hed(msd_admin_datepicker_gTxt("preferences"),1),2)).
tr(tdcs(hed(msd_admin_datepicker_gTxt("instructions"),4),2)).
tr(tda(msd_admin_datepicker_gTxt("field"), ' style="text-align:right;vertical-align:middle"').td(text_input("msd_datepicker_customfield",$msd_datepicker_customfield,'20'))).
tr(tda(msd_admin_datepicker_gTxt("jqueryui"), ' style="text-align:right;vertical-align:middle"').td(text_input("msd_datepicker_jqueryui",$msd_datepicker_jqueryui,'20'))).
tr(tda(msd_admin_datepicker_gTxt("jqueryuicss"), ' style="text-align:right;vertical-align:middle"').td(text_input("msd_datepicker_jqueryui_css",$msd_datepicker_jqueryui_css,'20'))).
tr(tda(msd_admin_datepicker_gTxt("dateformat"), ' style="text-align:right;vertical-align:middle"').td(text_input("msd_datepicker_format",$msd_datepicker_format,'20'))).
tr(tda(gTxt(msd_admin_datepicker_gTxt("articledate")), ' style="text-align:right;vertical-align:middle"').td(yesnoradio("msd_datepicker_posted",$msd_datepicker_posted))).
tr(tda(gTxt(msd_admin_datepicker_gTxt("expiredate")), ' style="text-align:right;vertical-align:middle"').td(yesnoradio("msd_datepicker_expire",$msd_datepicker_expire))).
tr(tda(fInput("submit","save",gTxt("save_button"),"publish").eInput("msd_admin_datepicker_options").sInput('saveprefs'), " colspan='2' class='noline'")).
endTable());
}

#
#	MPL Support
#
function msd_datepicker_enumerate_strings($event , $step='' , $pre=0)
	{
	global $msd_datepicker_strings;
	$r = array	(
				'owner'	=> 'msd_admin_datepicker',		#	Change to your plugins name
				'prefix'	=> MSD_DATEPICKER_PREFIX,		#	Its unique string prefix
				'lang'	=> 'en-us',					#	The language of the initial strings.
				'event'	=> 'admin',					#	public/admin/common = which interface the strings will be loaded into
				'strings'	=> $msd_datepicker_strings,		#	The strings themselves.
				);
	return $r;
	}
#
#	MPL Support
#
function msd_admin_datepicker_gTxt( $what , $args = array() )
	{
	global $textarray;
	global $msd_datepicker_strings;

	#
	#	Prepare the prefixed key for use...
	#
	$key = MSD_DATEPICKER_PREFIX . '-' . $what;
	$key = strtolower($key);

	#
	#	Grab from the global textarray (possibly edited by MLP) if we can...
	#
	if(isset($textarray[$key]))
		{
		$str = $textarray[$key];
		}
	else
		{
		#
		#	The string isnt in the localised $textarray so fallback to using
		# the string array in the plugin (which is not prefixed.)
		#
		$key = strtolower($what);

		if( isset( $msd_datepicker_strings[$key] ) )
			$str = $msd_datepicker_strings[$key];
		else
			#
			#	Fallback to returning the key if the string is not present...
			#
			$str = $what;
		}

	#
	#	If needed, perform substitutions...
	#
	if( !empty($args) )
		$str = strtr( $str , $args );

	return $str;
	}
#
#Install Preferences
#
function msd_admin_datepicker_install(){
global $prefs;
if (!isset($prefs['msd_datepicker_jqueryui'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_jqueryui',
		val = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js',
		html = 'text_input',
		prefs_id = 1,
		type = 2,
		event = 'publish',
		position = 0
		");
}
if (!isset($prefs['msd_datepicker_customfield'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_customfield',
		val = '#custom-1',
		html = 'text_input',
		prefs_id = 1,
		type = 2,
		event = 'publish',
		position = 0
		");
}
if (!isset($prefs['msd_datepicker_jqueryui_css'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_jqueryui_css',
		val = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css',
		html = 'text_input',
		prefs_id = 1,
		type = 2,
		event = 'publish',
		position = 0
		");
}
if (!isset($prefs['msd_datepicker_format'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_format',
		val = 'mm/dd/yyyy',
		html = 'text_input',
		prefs_id = 1,
		type = 2,
		event = 'publish',
		position = 0
		");
}
if (!isset($prefs['msd_datepicker_region'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_region',
		val = 'en',
		html = 'text_input',
		prefs_id = 1,
		type = 2,
		event = 'publish',
		position = 0
		");
}
if (!isset($prefs['msd_datepicker_posted'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_posted',
		val = '0',
		prefs_id = 1
		");
}   
if (!isset($prefs['msd_datepicker_expire'])){
	safe_insert('txp_prefs', "
		name = 'msd_datepicker_expire',
		val = '0',
		prefs_id = 1
		");
} 
}
#
#Uninstall Preferences
#
function msd_admin_datepicker_uninstall(){
global $prefs;
if (isset($prefs['msd_datepicker_jqueryui'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_jqueryui'");
}
if (isset($prefs['msd_datepicker_customfield'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_customfield'");
}
if (isset($prefs['msd_datepicker_jqueryui_css'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_jqueryui_css'");
}
if (isset($prefs['msd_datepicker_format'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_format'");
}      
if (isset($prefs['msd_datepicker_region'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_region'");
}
if (isset($prefs['msd_datepicker_posted'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_posted'");
}
if (isset($prefs['msd_datepicker_expire'])){
	safe_delete('txp_prefs', "
		name = 'msd_datepicker_expire'");
}    
}
#
#Calendar Icon
#
function msd_admin_datepicker_icon_jquery(){
	while(@ob_end_clean());
	header("Content-Type: image/gif");
	header("Expires: ".date("r", time()+3600));
	header("Cache-Control: public");
	echo base64_decode
('R0lGODlhEAAPAPQAAIyq7zlx3lqK5zFpznOe7/729fvh3/3y8e1lXt1jXO5tZe9zbLxeWfB6c6lb
V/GDffKIgvKNh/OYkvSblvSinfWrp3dTUfawq/e1sf3r6v/8/P/9/f///////wAAAAAAACH5BAEA
AB0ALAAAAAAQAA8AAAWK4GWJpDWN6KU8nNK+bsIxs3FdVUVRUhQ9wMUCgbhkjshbbkkpKnWSqC84
rHA4kmsWu9lICgWHlQO5lsldSMEgrkAaknccQBAE4mKtfkPQaAIZFw4TZmZdAhoHAxkYg25wchAB
AQMDeIRYHF5gEkcSBo2YEGlgEEcQoI4SDRWrrayrFxCDDrW2t7ghADs=');
}
function msd_admin_datepicker_icon_fam_fam(){
	while(@ob_end_clean());
	header("Content-Type: image/png");
	header("Expires: ".date("r", time()+3600));
	header("Cache-Control: public");
	echo base64_decode
('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAI1SURBVDjLpZPNS5RRFIef98NRG3M05gOaqMhCAoskEFtVO2kT5DZo1SZoW9EiFGrVok1/QhRGmlHYJoQy8wuJIoLQ0iH8nCGcMmzm3ntOi1edWbQJLxzOPZvffc7v3OOpKjs5IcCDkbVbqlx2KvtEBCdgRXBOcKJYJ1XhcFZxIlN3Lh7pCAFE9Wp3x+7k/7zc0zd7fJvAiSQB4v1XQBWcBXFgTHQvl8CUoWTAGH7fGMYYV1slsOWDwt4UiI1C7aZICUwJbBk+LwFgrKt44JxsCniwmAeViEQkInFbGchkAChvCqCq3H+5pOsbRh+OrKiqat/bZVVVffwuqp+MRfXgeJTzxQ29dG9KVTUiME4QVcIA+sdWCQKfgfFVwgCeTa4yunKbN4OCilAz3cPR7C7KJiLwt1pQIAw8uk+lCX240JmmxofzHWl8L6C15TC+H3DuZCYarZWKB8YJKhD68GI6z2ThLhNDiqoSvr+O73vMzecI/ICnEytkEz5KtYAVVJWaALraU4wNwaEDB/mWm6erPUXg3aSztRlxysxCkT2NtcRrw0oLViK1wPd49aEAwFwuh4fH8McCRkBEmV0s0tQQI9lYtz25EMBaG3ngw9ljScLgGmfakrz+VOB0W5KB8TxfF36SiMdIJeoQUQKfCoFxUQtt+xtY+rFBS6aeueV1ss0xvnwvkk1AoiFGuqk+Ig08RFSqPpKO9j6aOVF2EjfWYazDWcE4wTr7z11Y+/XnOYC303X+CyNCWo09HetwAAAAAElFTkSuQmCC');
}

# --- END PLUGIN CODE ---
if (0) {
?>
<!--
# --- BEGIN PLUGIN HELP ---
h1(title). msd_admin_datepicker
h2(section). Features

p. Adds a jQuery UI Datepicker to the Article Write page allowing authors to easily associate a custom formated date with each article.

h2(section). Setup

p. Set the "plugin preferences":/textpattern/index.php?event=plugin_prefs.msd_admin_datepicker to configure your date picker. Set the Date Custom Field to the "jQuery Selector":http://docs.jquery.com/Selectors for the input you want to use.  Need multiple date pickers? Use multiple selectors, separated with a comma. It's all jQuery goodness.

p. Optionally use datepicker for setting the Article Posted and/or Expire dates.
# --- END PLUGIN HELP ---
-->
<?php
}
?>